package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //获得本次请求的URI
        String uri = request.getRequestURI();

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断本次请求是否需要登录,才可以访问
            if( check(urls, uri)){
                //如果不需要，直接放行
                chain.doFilter(request,response);
                return;
            }

        //判断登录状态,如果已登录,则直接放行
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        Long user = (Long) session.getAttribute("user");
        if(employee!=null){
            //如果已经登录，把用户id存入线程中,然后直接放行
            log.info("用户已登录,用户id为:{}",session.getAttribute("employee"));
            Long empId = (Long) session.getAttribute("employee");
            BaseContext.setCurrentId(empId);
            log.info("用户ip地址为:{}",request.getRemoteAddr());
            //放行
            chain.doFilter(request,response);
            /*response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));*/
            return;
        }
        if(user!=null){
            Long userId = (Long) session.getAttribute("user");
            BaseContext.setCurrentId(userId);
            chain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;



    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
